// 登录接口
const express = require("express");

const router = express.Router();

const bcrypt = require("bcrypt");

const gravatar = require("gravatar");
// 增加token
const jwt = require("jsonwebtoken");

const User = require("../../model/user");
const keys = require("../../config/key").secretOrkey;
const passport = require("passport");

/**
 * @$route get
 * @desc 返回数据
 * @access public
 */
router.get("/test", (req, res) => {
	res.json({
		msg: "login work",
	});
});

/**
 * @$route post
 * @desc 注册接口
 * @access public
 */
router.post("/register", (req, res) => {
	console.log("req.body", req.body);
	// 查询数据库中有无当前数据
	User.findOne({ email: req.body.email }).then((user) => {
		if (user) {
			return res.status(400).json({ msg: "邮箱已被注册!" });
		} else {
			const avatar = gravatar.url(req.body.email, {
				s: "200",
				r: "pg",
				d: "mm",
			});
			const newUser = new User({
				userName: req.body.userName,
				email: req.body.email,
				avatar: `http://p2.music.126.net/64Ojn1z1L4FrLrCggMGlhw==/109951166667803297.jpg?param=140y140`,
				password: req.body.password,
				identity: req.body.identity,
			});
			bcrypt.genSalt(10, function (err, salt) {
				bcrypt.hash(newUser.password, salt, (err, hash) => {
					if (err) throw err;

					newUser.password = hash;

					newUser
						.save()
						.then((user) => res.json(user))
						.catch((err) => console.log(err));
				});
			});
		}
	});
});

/**
 * @$route post api/user/curcent
 * @desc 登录接口
 * @access public
 */
router.post("/login", (req, res) => {
	console.log("req.body", req.body);
	// 查询数据库中有无当前数据

	const email = req.body.email;
	const password = req.body.password;
	User.findOne({ email }).then((user) => {
		if (user) {
			// bcrypt.compare(password, user.password).then((isMatch) => {
			// 	if (isMatch) {
			// 		res.json({
			// 			msg: "success",
			// 		});
			// 	} else {
			// 		return res.status(400).json({ email: "密码错误!" });
			// 	}
			// });
			bcrypt.compare(password, user.password).then((isMatch) => {
				if (isMatch) {
					const rules = {
						id: user.id,
						userName: user.userName,
						avatar: user.avatar,
						identity: user.identity,
					};
					jwt.sign(rules, keys, { expiresIn: 3600 }, (err, token) => {
						if (err) throw err;
						res.json({
							success: true,
							token: "Bearer " + token,
						});
					});
				} else {
					return res.status(400).json({ msg: "密码错误!" });
				}
			});
		} else {
			return res.status(404).json({ msg: "用户不存在!" });
		}
	});
});

/**
 * @$route GET api/user/current
 * @desc  return current user
 * @access private
 */
router.get(
	"/current",
	passport.authenticate("jwt", { session: false }),
	(req, res) => {
		console.log(req);
		res.json({
			id: req.user.id,
			userName: req.user.userName,
			email: req.user.email,
			identity: req.user.identity,
		});
	}
);

module.exports = router;
